package cn.tedu.boot.ers.service.impl;


import cn.tedu.boot.ers.config.Constant;
import cn.tedu.boot.ers.entity.Product;
import cn.tedu.boot.ers.exception.ServiceException;
import cn.tedu.boot.ers.mapper.ProductMapper;
import cn.tedu.boot.ers.pojo.dto.AddProductDTO;
import cn.tedu.boot.ers.pojo.dto.ProductListDTO;
import cn.tedu.boot.ers.pojo.query.ProductListQuery;
import cn.tedu.boot.ers.pojo.vo.CategoryVO;
import cn.tedu.boot.ers.pojo.vo.ProductVO;
import cn.tedu.boot.ers.service.CategoryService;
import cn.tedu.boot.ers.service.ProductService;
import cn.tedu.boot.ers.web.State;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @Description: 商品服务实现类
 * @Author: han
 * @Date: 2022/6/11
 **/
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    ProductMapper productMapper;

    @Autowired
    CategoryService categoryService;


    @Override
    public void add(AddProductDTO addProductDTO) {
//        添加商品,new对象
        Product product = new Product();
//        自动赋值属性
        BeanUtils.copyProperties(addProductDTO,product);
//        防止商品重名,自动装载
        //获取添加商品名
        String productName = addProductDTO.getTitle();
        //用添加商品名在数据库中是否查得到
        ProductVO productOld = productMapper.selectByTitle(productName);
        if (productOld !=null) {
            throw new ServiceException(State.ERR,"商品已存在");
        }
        int count = productMapper.insertSelective(product);
        if (count == 0) {
            throw new ServiceException(State.ERR,"插入失败");
        }

    }

    @Override
    public void update(Product updateProduct){
    //        查询数据库是否有该商品名
        ProductVO productOld = productMapper.selectByTitle(updateProduct.getTitle());
    //      同名且不同ID,不存在不能修改,抛出异常
        if (productOld !=null && !productOld.getId().equals(updateProduct.getId()) ) {
            throw new ServiceException(State.ERR,"商品名已存在");
        }
        int count = productMapper.updateByPrimaryKeySelective(updateProduct);
        if (count == 0) {
            throw new ServiceException(State.ERR,"文件上传失败");
        }
    }

    @Override
    public void delete(Integer id){
//        查询数据库是否有该商品名
        ProductVO productOld = productMapper.selectByPrimaryKey(id.longValue());
//      同名且不同ID,不存在不能修改,抛出异常
        if (productOld ==null) {
            throw new ServiceException(State.ERR,"删除失败");
        }
        int count = productMapper.deleteByPrimaryKey(id.longValue());
        if (count == 0) {
            throw new ServiceException(State.ERR,"删除失败");
        }
    }

    @Override
    public void batchUpdateSellStatus(Integer[] ids, Integer sellStatus) {
        productMapper.batchUpdateSellStatus(ids, sellStatus);
    }

    @Override
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
        // 列表分页的方法,需要加载依赖
        PageHelper.startPage(pageNum, pageSize);
        List<Product> products = productMapper.selectListForAdmin();
        PageInfo pageInfo = new PageInfo(products);
        return pageInfo;
    }

    @Override
    public ProductVO detail(Long id) {
        ProductVO product = productMapper.selectByPrimaryKey(id);
        return product;
    }

    @Override
    public PageInfo list(ProductListDTO productListDTO) {
        ProductListQuery productListQuery = new ProductListQuery();

        //搜索处理
        if (!StringUtils.isEmpty(productListDTO.getKeyword())) {
            String keyword =
                    //StringBuilder合成字符串
                    new StringBuilder().append("%").append(productListDTO.getKeyword()).append("%").toString();
            productListQuery.setKeyword(keyword);
        }

        //目录处理: 如果查某个目录下的商品,不仅是需要查出该目录下的,还要把所有子目录的所有商品都查出来
        //,所以要拿到一个目录id的List
        if (productListDTO.getProductTypeId() != null) {
            List<CategoryVO> categoryVOList = categoryService.listCategoryForCustomer(productListDTO.getProductTypeId());
            ArrayList<Integer> categoryIds = new ArrayList<>();
            categoryIds.add(productListDTO.getProductTypeId());
            getCategoryIds(categoryVOList,categoryIds);
            productListQuery.setCategoryIds(categoryIds);
        }

        //排序处理
        String orderBy = productListDTO.getOrderBy();
        if (Constant.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)) {
            PageHelper.startPage(productListDTO.getPageNum(), productListDTO.getPageSize(), orderBy);
        } else {
            PageHelper.startPage(productListDTO.getPageNum(), productListDTO.getPageSize(), orderBy);
        }

        List<Product> productList = productMapper.selectList(productListQuery);
        PageInfo pageInfo = new PageInfo(productList);
        return pageInfo;

    }

    private void getCategoryIds(List<CategoryVO> categoryVOList, ArrayList<Integer> categoryIds) {
        for (int i = 0; i < categoryVOList.size(); i++) {
            CategoryVO categoryVO= categoryVOList.get(i);
            if (categoryVO != null) {
                categoryIds.add(categoryVO.getId());
                getCategoryIds(categoryVO.getChildCategory(),categoryIds);
            }
        }
    }
}
